package com.gxa;

import com.gxa.dao.UserDao;
import com.gxa.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EsDemo02BootApplicationTests02 {

        @Autowired
        private UserDao userDao;

        /**
         * 新增
         */
        @Test
        public void save(){
                User user = new User();
                user.setId(1);
                user.setName("zhangsan");
                user.setAge(20);
                user.setSex("M");

                userDao.save(user);

        }

        //修改
        @Test
        public void update(){
                User user = new User();
                user.setId(1);
                user.setName("lisi");
                user.setAge(20);
                user.setSex("M");

                userDao.save(user);
        }

        //根据id查询
        @Test
        public void findById(){
                User user = userDao.findById(1L).get();
                System.out.println(user);
        }

        //查询所有
        @Test
        public void findAll(){
                Iterable<User> users = userDao.findAll();
                for (User user : users) {
                        System.out.println(user);
                }
        }

        //删除
        @Test
        public void delete(){
                User user = new User();
                user.setId(1);
                userDao.delete(user);
        }

        //批量新增
        @Test
        public void saveAll(){
                List<User> userList = new ArrayList<>();
                for (int i = 0; i < 10; i++) {
                        User user = new User();
                        user.setId(i);
                        user.setName("lisi" +i);
                        user.setAge(20);
                        user.setSex("M");

                        userList.add(user);
                }
                userDao.saveAll(userList);
        }

        //分页查询
        @Test
        public void findByPageable(){
                //设置排序(排序方式，正序还是倒序，排序的id)
                Sort sort = Sort.by(Sort.Direction.DESC,"id");
                int currentPage=0;//当前页，第一页从0开始，1表示第二页
                int pageSize = 5;//每页显示多少条
                //设置查询分页
                PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
                //分页查询
                Page<User> users = userDao.findAll(pageRequest);
                for (User user : users.getContent()) {
                        System.out.println(user);
                }

        }

}
